class Solution {
public:
    bool isValid(string s) {
        int n = s.size();
        stack<int> stk;
        stk.push(s[0]);
        bool ans = n == 1 ? false : true;
        for(int i = 1; i < n; ++i)
        {
            if(s[i] == '(' || s[i] == '[' || s[i] == '{')
                stk.push(s[i]);
            else if(stk.empty())
            {
                ans = false;
                break;
            }
            else{
                switch(stk.top())
                {
                    case '(':
                    {
                        if(s[i] == ')')
                            stk.pop();
                        else ans = false;   
                        break; 
                    }
                    case '[':
                    {
                        if(s[i] == ']')
                            stk.pop();
                        else ans = false;   
                        break; 
                    }
                    case '{':
                    {
                        if(s[i] == '}')
                            stk.pop();
                        else ans = false;  
                        break; 
                    }
                }
            }

            
        }
        if(!stk.empty()) ans = false;
        return ans;
    }
};
